﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CefSharp;
using System.Dynamic;
using CefSharp.WinForms;
using System.Threading.Tasks;
using System.Threading;
using Common;
using System.Diagnostics;
namespace Brower
{
    public partial class Form1 : Form
    {
        ChromiumWebBrowser browser;
        Thread th=null;
        public static int index = 0;
        public Form1()
        {

            InitializeComponent();

            //Cef.Initialize(new CefSettings());
            //browser = new ChromiumWebBrowser("https://www.ickd.cn/");
            //this.Controls.Add(browser);
            //browser.Dock = DockStyle.Fill;
            ////////////执行js/////////////////////////////////
            //browser.IsBrowserInitializedChanged += OnIsBrowserInitializedChanged;
            //////////////////////////////////////////////////
            //browser.RequestHandler = new RequestHandler();
            //MessageBox.Show(browser.RequestContext.ToString());

            

        }
        private void OnIsBrowserInitializedChanged(object sender, IsBrowserInitializedChangedEventArgs args)
        {
            if (args.IsBrowserInitialized)
            {
                //browser.ExecuteScriptAsync("alert(\"hello world\")");
            }
        }
        private string GetHTMLFromWebBrowser()
        {
            browser.GetBrowser().MainFrame.ViewSource();
            Task<String> taskHtml = browser.GetBrowser().MainFrame.GetSourceAsync();
            string response = taskHtml.Result;
            return response;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            string path = "https://www.ickd.cn/";
            browser = new ChromiumWebBrowser(path);
            browser.Dock = DockStyle.Fill;//填充方式
            
            this.Controls.Add(browser);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            th = new Thread(new ThreadStart(begin));
            th.Start();
        }
        public void begin()
        {
            while (true)
            {
                if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 07:00:00")) && DateTime.Now < DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 18:00:00")))
                {

                    List<POrderInfo> list = CommonDAL.FindOrder();
                    int all = list.Count;
                    int count = 0;
                    
                    foreach (POrderInfo info in list)
                    {
                        count++;
                        browser.ExecuteScriptAsync("document.getElementById('mailNo').value='"+info.ExpressNum+"';");
                        browser.ExecuteScriptAsync("document.getElementById('submitButton').click();");
                        this.label1.Text = count + "/" + all;
                        Thread.Sleep(10000);
                        string html = GetHTMLFromWebBrowser();
                        if (html.Contains("亲，请输入以下验证码再继续哦"))
                        {
                            browser.Reload();
                            Thread.Sleep(20000);
                            CloseApp();
                            continue;
                        }
                        string table = Commons.GetTable(html);
                        List<string> tr = Commons.GetTr(table);
                        List<string> json = new List<string>();
                        foreach (string line in tr)
                        {
                            List<string> td = Commons.GetTd(line);
                            json.Add("{\"AcceptTime\":\"" + Commons.FilterHTML(td[0]) + "\",\"AcceptStation\":\"" + Commons.FilterHTML(td[2]).Replace("/站淘宝红包", "").Replace("淘宝红包", "") + "\"}");
                        }
                        string str = "{\"Success\":true,\"Traces\":[" + string.Join(",", json) + "]}";
                        CommonDAL.UpdateTrail(info.ID, str);
                        CloseApp();
                        Thread.Sleep(new Random().Next(5000, 10000));
                        CloseApp();
                    }
                    
                    Thread.Sleep(2000);
                    index++;
                }
                else
                {
                    Thread.Sleep(600000);
                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (th!=null)
            {
                th.Abort();
            }
        }
        public static void Log(string str)
        {
            string path = "C:/log.txt";
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true);//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine("=======================" + DateTime.Now + "=======================");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
        }

        public void CloseApp()
        {
            Process[] processes = Process.GetProcesses();
            foreach (Process p in processes)
            {
                if (p.ProcessName.Contains("notepad"))
                {
                    p.Kill();
                }
            }   
        }

        private void button2_Click(object sender, EventArgs e)
        {
            browser.Reload();
        }
    }
}
